#include "stm32f10x.h"                  // Device header

/*
初始化编码器的接口设置
*/
void Encoder_Init(void)
{
	// 不管干啥,先开启时钟!!!
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	
	// GPIOA初始化
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;				// How to choose ???
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);

	// 时基单元初始化
	TIM_TimeBaseInitTypeDef TIM3Base_InitStruture;
	TIM_TimeBaseStructInit(&TIM3Base_InitStruture);
	TIM3Base_InitStruture.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM3Base_InitStruture.TIM_CounterMode = TIM_CounterMode_Up;
	TIM3Base_InitStruture.TIM_Period = 65536 - 1;						// ARR
	TIM3Base_InitStruture.TIM_Prescaler = 1 - 1;						// PSC
	TIM3Base_InitStruture.TIM_RepetitionCounter = 0x00;					// None
	TIM_TimeBaseInit(TIM3, &TIM3Base_InitStruture);
	
	// 输入捕获设置  使用两个通道	
	TIM_ICInitTypeDef TIM_ICInitStruture;
	TIM_ICStructInit(&TIM_ICInitStruture);
	TIM_ICInitStruture.TIM_Channel = TIM_Channel_1;
	TIM_ICInitStruture.TIM_ICFilter = 0xF;
	TIM_ICInit(TIM3, &TIM_ICInitStruture);
	TIM_ICInitStruture.TIM_Channel = TIM_Channel_2;
	TIM_ICInitStruture.TIM_ICFilter = 0xF;
	TIM_ICInit(TIM3, &TIM_ICInitStruture);
	
	// 编码器设置
	TIM_EncoderInterfaceConfig(TIM3, TIM_EncoderMode_TI12, TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);
	
	// 使能定时器
	TIM_Cmd(TIM3, ENABLE);
}


/*
获取计数(测速)值
*/
int16_t Encoder_GetCNT(void)
{
	int16_t Temp;
	Temp = TIM_GetCounter(TIM3);
	TIM_SetCounter(TIM3, 0);				// 读完后清零
	return Temp;
}
